import React, { useEffect, useState } from 'react';
import { Button, Card, Input, Modal, message } from 'antd';
import './TemplateMainList.css'; // 自定义样式文件
import axios from 'axios'; // 用于发起 HTTP 请求
import { allData } from '../../type/index'; // 导入订单数据类型
import SelectList from '../SelectList/SelectList'
const OrderManagement: React.FC = () => {
    const [allList, setAllList] = useState<allData[]>([]); // 订单列表数据
    const [visibleCount, setVisibleCount] = useState(10); // 初始显示10条数据
    const [selectedItems, setSelectedItems] = useState<Set<string>>(new Set()); // 选中的订单ID集合
    const [shopName, setShopName] = useState(''); // 店铺名称
    const [productName, setProductName] = useState(''); // 商品名称

    // 获取订单列表数据
    const getData = async () => {
        try {
            const response = await axios.get("/api/allList"); // 发起 GET 请求获取订单数据
            const { code, allList } = response.data; // 解构响应数据
            if (code === 200) { // 如果请求成功
                setAllList(allList); // 更新订单列表数据
            }
        } catch (error) {
            console.error("Error fetching order list:", error); // 打印错误信息
        }
    };
    // 初始化时获取数据
    useEffect(() => {
        getData(); // 加载订单数据
    }, []); // 依赖数组为空，仅在组件挂载时执行一次

    // 添加滚动事件监听器
    useEffect(() => {
        const handleScroll = () => {
            const { scrollTop, clientHeight } = document.documentElement;
            const { scrollHeight } = document.body;
            // 检查是否到达底部
            if (scrollTop + clientHeight >= scrollHeight - 5) {
                setVisibleCount((prevCount) => prevCount + 10); // 每次加载10条
                message.success('已加载更多数据'); // 显示加载更多提示
            }
        };
        window.addEventListener('scroll', handleScroll);
        return () => {
            window.removeEventListener('scroll', handleScroll);
        };
    }, []);

    // 设置商品状态为“好货”
    const setAsGoodProduct = (id: string) => {
        setAllList((prevList) =>
            prevList.map((item) =>
                item.id === id ? { ...item, status: "好货" } : item
            )
        );
        message.success('设置成功，已将该商品设为好货！'); // 弹框提示设置成功
    };

    // 下架商品
    const shelveOrder = (id: string) => {
        setAllList((prevList) => {
            const updatedList = prevList.filter(item => item.id !== id); // 移除该商品
            const shelvedItem = prevList.find(item => item.id === id); // 获取移除的商品
            if (shelvedItem) {
                message.info('该商品已下架'); // 显示下架提示
            }
            return shelvedItem ? [...updatedList, shelvedItem] : updatedList; // 重新添加到列表末尾
        });
    };

    //删除单个
    const handelDel = (id: string) => {
        Modal.confirm({
            title: "删除",
            content: "您确定删除当前行数据吗?",
            onOk() {
                axios.get("/api/alldel", { params: { id } }).then((resp) => {
                    const { code, msg } = resp.data;
                    if (code === 200) {
                        message.success(msg);
                        //重新渲染数据
                        getData();
                    }
                });
            },
        });
    };

    // 切换单个商品的选择状态
    const toggleSelectItem = (id: string) => {
        setSelectedItems(prev => {
            const newSelected = new Set(prev);
            if (newSelected.has(id)) {
                newSelected.delete(id); // 如果已经选择，则取消选择
            } else {
                newSelected.add(id); // 如果未选择，则选择
            }
            return newSelected;
        });
    };

    // 全选/取消全选商品
    const selectAllItems = () => {
        if (selectedItems.size === allList.length) {
            setSelectedItems(new Set()); // 如果已全选，则取消全选
        } else {
            const newSelectedItems = new Set(allList.map(item => item.id));  // 选择所有
            setSelectedItems(newSelectedItems);
        }
    };
    // 批量选中的商品为“好货”并置顶
    const setSelectedAsGood = () => {
        setAllList(prevList => {
            const updatedList = prevList.map(item =>
                selectedItems.has(item.id) ? { ...item, status: "推荐" } : item
            );
            const recommendedItems = updatedList.filter(item => selectedItems.has(item.id));
            const nonRecommendedItems = updatedList.filter(item => !selectedItems.has(item.id));
            return [...recommendedItems, ...nonRecommendedItems];
        });
        message.success('选中的商品已设为推荐并置顶！');
        setSelectedItems(new Set());
    };
    // 输入框搜索功能
    const filteredList = allList.filter(item => {
        const matchesShopName = item.word.includes(shopName); // 假设 item 有 shopName 属性
        const matchesProductName = item.title.includes(productName);
        return matchesShopName && matchesProductName; // 满足两个条件
    });

    // 清空筛选条件
    const clearFilters = () => {
        setShopName('');
        setProductName('');
        setAllList(allList);
    };


    return (
        <div className='TemplateList-Box'>
            <Card style={{ marginBottom: '15px' }}>
                <div className='TemplateList-top'>
                    <div className='TemplateList-title1'>商品管理</div>
                    <SelectList></SelectList>
                    <div className="TemplateList-Con3">
                        <div>
                            <span>店铺名称:</span>
                            <Input
                                style={{ width: '220px', marginRight: '35px' }}
                                placeholder="请输入店铺名称"
                                value={shopName}
                                onChange={(e) => setShopName(e.target.value)} // 更新店铺名称
                            />

                        </div>
                        <div>
                            <span>商品名称:</span>
                            <Input
                                style={{ width: '190px' }}
                                value={productName}
                                onChange={(e) => setProductName(e.target.value)} // 更新商品名称
                            />
                        </div>
                    </div>

                </div>
                <Button style={{ width: '100px', marginLeft: '30px', backgroundColor: '#1a66ff', color: '#fff' }}>搜索</Button>
                <Button
                    style={{ width: '130px', marginLeft: '10px' }}
                    onClick={clearFilters}
                >
                    清空筛选条件
                </Button>
            </Card>
            <div className="TemplateList-Bott">
                <div className="TemplateList-Check">
                    <p>
                        <input
                            type="checkbox"
                            checked={selectedItems.size === allList.length}
                            onChange={selectAllItems}
                        />
                        <span style={{ marginLeft: '5px' }}>全选</span>
                    </p>
                    <Button
                        style={{ width: '120px', marginLeft: '10px' }}
                        onClick={setSelectedAsGood}
                    >
                        批量推荐
                    </Button>
                </div>
                <div className="TemplateList-Nav">
                    <p style={{ width: '600px', textAlign: 'center' }}>商品描述</p>
                    <p style={{ width: '220px', textAlign: 'center' }}>价格</p>
                    <p style={{ width: '230px', textAlign: 'center' }}>销量</p>
                    <p style={{ width: '200px', textAlign: 'center' }}>店铺</p>
                    <p style={{ width: '180px', textAlign: 'center' }}>创建时间</p>
                    <p style={{ width: '200px', textAlign: 'center' }}>操作</p>
                </div>
                <div className='Template-List'>
                    {
                        filteredList.slice(0, visibleCount).map((item) => (
                            <div key={item.id} className='goods'>
                                <div className='goodsinfomation'>
                                    <div className="goodsCheckBox">
                                        <input
                                            type="checkbox"
                                            checked={selectedItems.has(item.id)}
                                            onChange={() => toggleSelectItem(item.id)}
                                        />
                                    </div>
                                    <div className='goodsimage'>
                                        <img src={item.img} style={{ width: "100%", height: "100%" }} alt="" />
                                    </div>
                                    <div className='goodsName'>
                                        <h4>{item.title}</h4>
                                        <div>{item.address}<span>规格{item.number}公斤/箱</span><p>状态:<span style={{ color: 'red' }}>{item.status}</span></p></div>
                                    </div>
                                    <div className='goodsPrice'>￥{item.price}</div>
                                    <div className='goodsSize'>{item.size}</div>
                                    <div className='goodsWord'>{item.word}</div>
                                    <div className='goodsDate'>{item.date}</div>
                                    <div className='goodsDetail'>
                                        <p onClick={() => setAsGoodProduct(item.id)}>设为好货</p>
                                        <p onClick={() => shelveOrder(item.id)}>下架</p>
                                        <p onClick={() => handelDel(item.id)}>删除</p>
                                    </div>
                                </div>
                            </div>
                        ))
                    }
                </div>
            </div>
        </div>
    );
};


export default OrderManagement;